package com.reflection;

import java.lang.reflect.Field;

public class t3_成员变量 {
    public static void main(String[] args) throws Exception
    {
        //获取Class对象
        Class<?> clazz = Class.forName("com.reflection.Student");
        //1.获取公共成员变量
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        //2.获取所有的(私有的)
        Field[] f2 = clazz.getDeclaredFields();
        for (Field field : f2) {
            System.out.println(field);
        }
        //3.获取指定公共的成员变量
        Field g = clazz.getField("gender");

        //4.获取指定私有的成员变量
        Field a = clazz.getDeclaredField("age");


        //5.反射修改成员变量的值
        Student p = new Student("张三");
        Field gg = clazz.getField("gender");
        gg.set(p, "女");    //修改(设置)p对象的name
        String pp = (String) gg.get(p);//获取p对象的name
        System.out.println(pp);
        //6.暴力反射修改
        Student q = new Student("张三");
        Field aa = clazz.getDeclaredField("age");
        aa.setAccessible(true);
        aa.set(q,25);
        int qq = (int) aa.get(q);
        System.out.println(qq);
        
    }
}
